package com.acoreful.acf2java.admin.modules.auth.support.resolver;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.acoreful.acf2java.admin.modules.auth.exception.LoginRequiredException;
import com.acoreful.acf2java.admin.modules.auth.support.CurrentStaff;
import com.acoreful.acf2java.admin.modules.auth.support.SubjectContext;
import com.acoreful.acf2java.admin.modules.auth.support.annotation.Subject;

/**
 * 用于解析使用@Subject注解修饰的参数
 * 
 */
public class SubjectMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(Subject.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
            WebDataBinderFactory binderFactory) throws Exception {
        Subject annoSubject = parameter.getParameterAnnotation(Subject.class);
        CurrentStaff currentStaff = SubjectContext.getContext().getCurrentStaff();
        if (annoSubject.required() && currentStaff == null) {
            throw new LoginRequiredException();
        }
        return currentStaff;
    }
    
}
